import React, { useCallback, useMemo, useState } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Trash2, BookOpen, Library } from "lucide-react";
import { useToast } from "@/components/ui/use-toast";
import StandardImportModal from "./StandardImportModal";

export default function CompilationBasisTab({
  scheme,
  onUpdate,
  standards = [],
}) {
  const { toast } = useToast();
  const [isModalOpen, setIsModalOpen] = useState(false);

  
  const compilationBasis = useMemo(() => {
    if (!Array.isArray(scheme.compilationBasis)) return [];
    return scheme.compilationBasis.map((item) => {
      // 如果是纯ID字符串，尝试从standards中查找对应对象
      if (typeof item === "string") {
        const matchedStandard = standards.find(
          (standard) => standard.id === item
        );
        // 找到则返回完整对象，未找到则保留ID格式
        return matchedStandard ? matchedStandard : { id: item };
      }
      // 本身是对象则直接返回
      return item;
    });
  }, [scheme.compilationBasis, standards]);

  // 手动添加
  const handleAddItem = useCallback(() => {
    const newBasis = [...compilationBasis, ""];
    onUpdate({ compilationBasis: newBasis });
  }, [compilationBasis, onUpdate]);

  // 手动输入的
  const handleUpdateItem = useCallback(
    (index, value) => {
      const newBasis = [...compilationBasis];
      // 检查输入值是否可能是一个ID（非空字符串且在standards中存在对应对象）
      if (typeof value === "string" && value.trim()) {
        const matchedStandard = standards.find(
          (standard) => standard.id === value || standard.code === value
        );
        if (matchedStandard) {
          // 如果找到匹配的标准对象，存储完整对象
          newBasis[index] = matchedStandard;
        } else {
          // 否则存储为自定义文本对象（保留原始值）
          newBasis[index] = { id: Date.now().toString(), name: value };
        }
      } else {
        newBasis[index] = value;
      }
      onUpdate({ compilationBasis: newBasis });
    },
    [compilationBasis, onUpdate, standards]
  );
  // 手动添加-----移除
  const handleRemoveItem = useCallback(
    (index) => {
      const newBasis = compilationBasis.filter((_, i) => i !== index);
      onUpdate({ compilationBasis: newBasis });
    },
    [compilationBasis, onUpdate]
  );

  const handleImportStandards = useCallback(
    (selectedStandards) => {
      // 用Set存储已有的id来判断重复
      const existingIds = new Set(compilationBasis.map((item) => item.id));
      // const existingBasis = new Set(compilationBasis);
      const newItems = [];
      selectedStandards.forEach((standard) => {
        // 跳过没有id的标准（如果存在）
        if (!standard.id) return;
        // 已存在则跳过
        if (existingIds.has(standard.id)) return;

        // 格式化标准文本
        let standardText = "";
        if (standard.code && standard.name) {
          standardText = `${standard.code} ${standard.name}`;
        } else if (standard.name) {
          standardText = standard.name;
        } else if (standard.code) {
          standardText = standard.code;
        }

        // 添加发布年份信息
        if (standard.publicationYear && standardText) {
          standardText += ` (${standard.publicationYear})`;
        }
        newItems.push({
          ...standard,
        });
        existingIds.add(standard.id);
      });

      if (newItems.length > 0) {
        // 合并已有项和新项
        const updatedBasis = [...compilationBasis, ...newItems];
        onUpdate({ compilationBasis: updatedBasis });
        toast({
          title: "导入成功",
          description: `成功导入 ${newItems.length} 项标准规范。`,
        });
      } else {
        toast({
          title: "无新内容",
          description: "所选标准已在编制依据中。",
        });
      }

      setIsModalOpen(false);
    },
    [compilationBasis, onUpdate, toast]
  );

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span className="flex items-center gap-2">
              <BookOpen
                className="w-5 h-5 text-blue-600"
                onClick={() => {
                  console.log(standards, 90000);
                  console.log(scheme, "schemescheme");
                }}
              />
              编制依据
              <Badge
                variant="outline"
                className="bg-blue-50 text-blue-700 border-blue-200"
              >
                {compilationBasis.length} 项
              </Badge>
            </span>
            <div className="flex items-center gap-2">
              <Button
                onClick={() => setIsModalOpen(true)}
                variant="outline"
                size="sm"
              >
                <Library className="w-4 h-4 mr-2" />
                从知识库选择
              </Button>
            </div>
          </CardTitle>
          <CardDescription>
            添加本方案编制所依据的标准、规范、文件等。您可以手动输入，或从知识库中选择标准规范。
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {compilationBasis.length === 0 ? (
            <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
              <BookOpen className="w-12 h-12 mx-auto mb-4 text-gray-300" />
              <p>暂无编制依据</p>
              <p className="text-sm">请点击右上角按钮添加</p>
            </div>
          ) : (
            compilationBasis.map((basis, index) => (
              <div
                key={`basis-item-${index}`}
                className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg"
              >
                <span className="text-sm font-medium text-gray-600 min-w-8">
                  {index + 1}.
                </span>
                <Input
                  key={`input-${index}`}
                  value={basis.name || ""}
                  onChange={(e) => handleUpdateItem(index, e.target.value)}
                  placeholder="输入编制依据"
                  className="flex-1"
                  disabled
                />
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleRemoveItem(index)}
                  className="text-red-500 hover:text-red-700 hover:bg-red-50"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            ))
          )}
        </CardContent>
      </Card>

      <StandardImportModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onImport={handleImportStandards}
        availableStandards={standards}
      />
    </>
  );
}
